<template>
  <div>
    <div class="search">
      <input v-model="keyWord" class="search-input" type="text" placeholder="输入城市名或拼音" />
    </div>
    <div class="search-content" ref="search" v-show="keyWord">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="city of list"
          :key="city.id"
          @tap="handleCityClick(city.name)"
        >{{city.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoMatch">暂无匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
import { mapMutations } from "vuex";

export default {
  name: "CitySearch",
  props: {
    allCities: Object
  },
  data() {
    return {
      keyWord: "",
      list: [],
      timer: null
    };
  },
  methods: {
    ...mapMutations({
      updateCity: "updateCity"
    }),
    handleCityClick(city) {
      this.updateCity(city);
      this.keyWord = "";
      this.$router.push("/");
    }
  },
  watch: {
    keyWord() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyWord) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const res = [];
        for (let i in this.allCities) {
          this.allCities[i].forEach(value => {
            if (
              value.spell.includes(this.keyWord) ||
              value.name.includes(this.keyWord)
            ) {
              res.push(value);
            }
          });
        }
        this.list = res;
      }, 100);
    },
    allCities() {
      this.scroll = new BScroll(this.$refs.search, {
        mouseWheel: true,
        tap: true,
        click: true
      });
    }
  },
  computed: {
    hasNoMatch() {
      return !this.list.length;
    }
  },
  mounted() {
    // this.scroll = new BScroll(this.$refs.search, {
    //   mouseWheel: true,
    //   tap: true
    // });
  }
};
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl';

.search {
  height: 0.72rem;
  padding: 0.1rem;
  background: $bgColor;

  .search-input {
    box-sizing: border-box;
    text-align: center;
    width: 100%;
    height: 0.62rem;
    padding: 0.1rem;
    line-height: 0.62rem;
    border-radius: 0.06rem;
    color: #666;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.78rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #eee;

  .search-item {
    text-align: left;
    line-height: 0.62rem;
    padding-left: 0.2rem;
    background: #fff;
    color: #666;
  }
}
</style>